package com.california.pay.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.california.pay.common.id.IdWorker;
import com.california.pay.common.utils.DateUtils;
import com.california.pay.config.CommonErrors;
import com.california.pay.consts.Status;
import com.california.pay.exception.BusinessException;
import com.california.pay.persist.domain.MchPayQuota;
import com.california.pay.persist.domain.TerminalLogin;
import com.california.pay.persist.mapper.MchPayQuotaMapper;
import com.california.pay.persist.mapper.TerminalLoginMapper;
import com.california.pay.socket.TransSocketMessage;
import com.google.common.collect.Maps;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.Date;
import java.util.Map;


@Slf4j
@Service
public class TerminalHeartbeatService {
    @Autowired
    private TerminalLoginMapper loginMapper;
    @Autowired
    private TerminalLoginService loginService;
    @Autowired
    private MchPayQuotaMapper quotaMapper;
    @Autowired
    private IdWorker idWorker;

    @Transactional(rollbackFor = {Exception.class})
    public Map<String, String> clientHeaxrtbeat(TransSocketMessage socketMessage, Channel channel){
        Date now = new Date();
        String message = socketMessage.getMessage();
        if (StringUtils.isBlank(message)) {
            throw new BusinessException(CommonErrors.INVALID_PARAM, "心跳接口，message不为空");
        }

        Map<String, String> msgMap = JSON.parseObject(message, new TypeReference<Map<String, String>>() {
        });

        String clientId = msgMap.get("clientId");
        String clientTime = msgMap.get("clientTime");
        String channelUserId = msgMap.get("channelUserId");

        TerminalLogin login = loginService.getTerminalLogin(clientId);

        if (login != null){
            TerminalLogin updateLogin = new TerminalLogin();
            updateLogin.setLoginId(login.getLoginId());
            updateLogin.setUpdateTime(now);
            updateLogin.setRecvHeartbeatTime(now);
            updateLogin.setChannelUserId(channelUserId);
            //updateLogin.setNettyChannelId(channel.id().asLongText());

            try {
                updateLogin.setClientHeartbeatTime(DateUtils.yyyyMMddHHmmss(clientTime));
            } catch (ParseException e) {
                log.error("时间格式转换出错，clientTime=" + clientTime, e);
                throw new BusinessException(CommonErrors.INVALID_PARAM, "时间格式转换出错,clientTime");
            }

            loginMapper.updateByPrimaryKeySelective(updateLogin);

            login = loginMapper.selectByPrimaryKey(login.getLoginId());

            Long payDate = Long.parseLong(DateUtils.yyyyMMdd(now));
            MchPayQuota mchPayQuota = quotaMapper.selectOneByMchIdAndPayDate(payDate, login.getChannelMchId());

            if (mchPayQuota == null){
                MchPayQuota record = new MchPayQuota();
                record.setQuotaId(idWorker.nextIdString());
                record.setChannelMchId(login.getChannelMchId());
                record.setPayTotalAmount(0L);
                record.setPayDate(payDate);
                record.setCreateTime(now);
                record.setUpdateTime(now);
                record.setVersion(0);
                record.setStatus(Status.USABLE);
                quotaMapper.insertSelective(record);
            }
        }

        Map<String, String> rspMap = Maps.newHashMap();
        rspMap.put("channelUserId", DateUtils.yyyyMMddHHmmss(now));
        rspMap.put("clientId", clientId);
        return rspMap;
    }




}
